const path = require("path");
const express = require("express");
const cors = require("cors");
const morgan = require("morgan");
var expressJWT = require('express-jwt');
const { init: initDB, Counter } = require("./db");
const Router = require('./routes/index');
const { secretKey } = require('./config/config')
const logger = morgan("tiny");

const app = express();
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(cors());
app.use(logger);



app.use(expressJWT({ secret: secretKey, algorithms: ['HS256'] }).unless({
  path: ['/apis/wxLogin'],
}))


app.use('/apis', Router);
app.get("/", async (req, res) => {
  res.sendFile(path.join(__dirname, "index.html"));
});

// // 小程序调用，获取微信 Open ID
// app.get("/api/wx_openid", async (req, res) => {
//   if (req.headers["x-wx-source"]) {
//     res.send(req.headers["x-wx-openid"]);
//   }
// });
app.use((err, req, res, next) => {
  // 这次错误是由 token 解析失败导致的
  console.log(err.name);

  if (err.name === "UnauthorizedError") {
    return res.send({
      status: 401,
      message: "无效的token",
    });
  }
  res.send({
    status: 500,
    message: "未知的错误",
  });
});

const port = process.env.PORT || 8080;

async function bootstrap() {
  await initDB();
  app.listen(port, () => {
    console.log("启动成功", port);
  });
}

bootstrap();
